package pers.wwz.study.redislock.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.wwz.study.redislock.utils.RedisLockUtils;

@RestController
@RequestMapping("/lock")
public class LockController {

    public static final int LOCK_EXPIRE_TIME = 10000;

    private static final Logger log = LoggerFactory.getLogger(LockController.class);

    @Autowired
    RedisLockUtils redisLockUtils;

    @RequestMapping("/getLock")
    public void getLock(){
        //设置个Key
        String key = "order_id";
        try {
            boolean b = redisLockUtils.lock(key,LOCK_EXPIRE_TIME);
            if (b) {
                String threadName = Thread.currentThread().getName();
                log.info("线程名称:{}",threadName);
                log.info("开始执行业务逻辑");
                Thread.sleep(1000);
            } else {
                log.info("获取锁失败{}", b);
                return;
            }
        } catch (Exception e) {
            log.info("获取锁异常{}", e);
        } finally {
            //删除锁；
            redisLockUtils.deleteLock(key);
        }
    }
}
